package com.telecom.aspect.interceptor;

import com.telecom.common.context.UserContext;
import com.telecom.common.convention.errorcode.BaseErrorCode;
import com.telecom.common.convention.exception.ClientException;
import com.telecom.common.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    // 角色常量
    private static final int ROLE_USER = 0;   // 普通用户
    private static final int ROLE_ADMIN = 1;  // 管理员

    @Resource
    JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        if (!StringUtils.hasText(authHeader)) {
            throw new ClientException("缺少认证头信息", BaseErrorCode.UNAUTHORIZED);
        }

        // 检查Bearer前缀
        if (!authHeader.startsWith("Bearer ")) {
            throw new ClientException("认证头格式错误", BaseErrorCode.UNAUTHORIZED);
        }

        // 提取token
        String token = authHeader.substring(7);
        if (!StringUtils.hasText(token)) {
            throw new ClientException("Token不能为空", BaseErrorCode.UNAUTHORIZED);
        }

        // 解析JWT并提取用户信息
        TokenPayload payload = jwtUtils.parseUser(token);

        // 将用户ID存入上下文
        UserContext.setUser(payload.getUserId());

        // 权限验证
        String requestURI = request.getRequestURI();
        Integer userRole = payload.getRole();

        // 检查管理员接口权限
        if (requestURI.startsWith("/admin/")) {
            if (userRole == null || !userRole.equals(ROLE_ADMIN)) {
                log.warn("非管理员用户尝试访问管理员接口: userId={}, role={}, uri={}",
                        payload.getUserId(), userRole, requestURI);
                throw new ClientException("权限不足，无法访问该接口", BaseErrorCode.FORBIDDEN);
            }
        }
        
        // 检查普通用户接口权限
        if (requestURI.startsWith("/user/")) {
            if (userRole == null || (!userRole.equals(ROLE_USER))) {
                log.warn("未授权用户尝试访问用户接口: userId={}, role={}, uri={}",
                        payload.getUserId(), userRole, requestURI);
                throw new ClientException("权限不足，无法访问该接口", BaseErrorCode.FORBIDDEN);
            }
        }

        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserContext.removeUser();
    }


}
